﻿using DevExpress.DXperience.Demos;
using DevExpress.Utils;
using DevExpress.XtraBars;
using DevExpress.XtraCharts;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevMy;
using DevMy.PublicClass;
using DevMy.PublicSetUp;
using MDIDemo.Model;
using MDIDemo.PublicClass;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Xceed.Document.NET;
using Xceed.Words.NET;
using BorderStyle = Xceed.Document.NET.BorderStyle;

namespace MDIDemo
{
    public partial class Form_welCome : DevExpress.XtraEditors.XtraForm
    {
        public Form_welCome(Form_NewMain form_NewMain)
        {
            InitializeComponent();
            this.form_NewMain = form_NewMain;
            equipmentAddress = -1;
        }
        private Form_NewMain form_NewMain;
        private int Count = 2;
        private WaitDialogForm waitDialogForm;
        private Class_MySqlDataBase class_MySqlDataBase;
        private int equipmentAddress;

        private void SocketNewDataReceive(object sender, EventArgs e)
        {
            if (this.IsActive)
            {
                DisplayMain(e as IniEquipmentDateModel);
            }
        }

        private void DisplayMain(IniEquipmentDateModel iniEquipmentDateModel)
        {
            int channel = iniEquipmentDateModel.channel + 1;
            if (this.equipmentAddress == iniEquipmentDateModel.address)
            {
                ChartControl waveChartControl, powerChartControl;
                switch (channel)
                {
                    case 1:
                        waveChartControl = this.chartControl1;
                        powerChartControl = this.chartControl7;
                        break;
                    case 2:
                        waveChartControl = this.chartControl2;
                        powerChartControl = this.chartControl8;
                        break;
                    case 3:
                        waveChartControl = this.chartControl3;
                        powerChartControl = this.chartControl9;
                        break;
                    case 4:
                        waveChartControl = this.chartControl4;
                        powerChartControl = this.chartControl10;
                        break;
                    case 5:
                        waveChartControl = this.chartControl5;
                        powerChartControl = this.chartControl11;
                        break;
                    case 6:
                        waveChartControl = this.chartControl6;
                        powerChartControl = this.chartControl12;
                        break;
                    default:
                        waveChartControl = this.chartControl1;
                        powerChartControl = this.chartControl7;
                        break;
                }
                foreach (DevExpress.XtraCharts.Series item in waveChartControl.Series)
                {
                    if (item.Points.Count > 100)
                        item.Points.RemoveRange(0, 7);
                }
                foreach (DevExpress.XtraCharts.Series item in powerChartControl.Series)
                {
                    if (item.Points.Count > 100)
                        item.Points.RemoveRange(0, 7);
                }
                DateTime dateTime = DateTime.Now;
                if (iniEquipmentDateModel.dataBatchModels.Count > 0)
                {
                    for (int i = 0; i < iniEquipmentDateModel.dataBatchModels.Count / 2; i++)
                    {
                        SeriesPoint seriesPoint1 = new SeriesPoint(dateTime.AddSeconds(i).ToString("hh:mm:ss")
                            , float.Parse(Convert.ToDecimal(iniEquipmentDateModel.dataBatchModels[i].waveValue).ToString("f4")));
                        SeriesPoint seriesPoint17 = new SeriesPoint(dateTime.AddSeconds(i).ToString("hh:mm:ss")
                            , float.Parse(Convert.ToDecimal(iniEquipmentDateModel.dataBatchModels[i].powerValue).ToString("f2")));
                        waveChartControl.Series[0].Points.Add(seriesPoint1);
                        powerChartControl.Series[0].Points.Add(seriesPoint17);
                        if (i + 7 < iniEquipmentDateModel.dataBatchModels.Count)
                        {
                            SeriesPoint seriesPoint2 = new SeriesPoint(dateTime.AddSeconds(i).ToString("hh:mm:ss")
                                , float.Parse(Convert.ToDecimal(iniEquipmentDateModel.dataBatchModels[i + 7].waveValue).ToString("f4")));
                            SeriesPoint seriesPoint27 = new SeriesPoint(dateTime.AddSeconds(i).ToString("hh:mm:ss")
                                , float.Parse(Convert.ToDecimal(iniEquipmentDateModel.dataBatchModels[i + 7].powerValue).ToString("f2")));
                            waveChartControl.Series[1].Points.Add(seriesPoint2);
                            powerChartControl.Series[1].Points.Add(seriesPoint27);
                        }
                    }
                }
            }
        }


        private void SetCompoment()
        {
            System.Drawing.Size size = this.Size;
            int XWidth = (size.Width - 4) / 2;

            SetChartControl(this.chartControl1, "实时波长数据", this.Count, "波长", XWidth);
            SetChartControl(this.chartControl2, "实时波长数据", this.Count, "波长", XWidth);
            SetChartControl(this.chartControl3, "实时波长数据", this.Count, "波长", XWidth);
            SetChartControl(this.chartControl4, "实时波长数据", this.Count, "波长", XWidth);
            SetChartControl(this.chartControl5, "实时波长数据", this.Count, "波长", XWidth);
            SetChartControl(this.chartControl6, "实时波长数据", this.Count, "波长", XWidth);

            SetChartControl(this.chartControl7, "实时能量数据", this.Count, "能量", XWidth);
            SetChartControl(this.chartControl8, "实时能量数据", this.Count, "能量", XWidth);
            SetChartControl(this.chartControl9, "实时能量数据", this.Count, "能量", XWidth);
            SetChartControl(this.chartControl10, "实时能量数据", this.Count, "能量", XWidth);
            SetChartControl(this.chartControl11, "实时能量数据", this.Count, "能量", XWidth);
            SetChartControl(this.chartControl12, "实时能量数据", this.Count, "能量", XWidth);

            this.xtraTabControl1.SelectedTabPage = this.xtraTabPage1;

            Class_PublicMethod class_PublicMethod = new Class_PublicMethod();
            Class_DataBaseConDefault class_DataBaseConDefault = new Class_DataBaseConDefault();
            class_DataBaseConDefault = class_PublicMethod.FromXmlToDefaultValueObject<Class_DataBaseConDefault>("DataBaseDefaultValues");

            class_MySqlDataBase = new Class_MySqlDataBase(class_DataBaseConDefault.dataSourceUrl
                , class_DataBaseConDefault.dataBaseName
                , class_DataBaseConDefault.dataSourceUserName
                , class_DataBaseConDefault.dataSourcePassWord
                , class_DataBaseConDefault.Port);

            DataTable dataTable = new DataTable();
            DataTable dataTableEquipment = new DataTable();
            dataTable = class_MySqlDataBase.GetDataTable("SELECT id,projectName FROM vou_project ORDER BY createDate DESC");
            dataTableEquipment = class_MySqlDataBase.GetDataTable("Select id, equipmentName From vou_equipment ORDER BY sortNo");
            if ((dataTable != null && dataTable.Rows.Count > 0) || (dataTableEquipment != null && dataTableEquipment.Rows.Count > 0))
            {
                LinkPersistInfo[] barButtonItemsProject = new LinkPersistInfo[dataTable != null ? dataTable.Rows.Count : 0];
                LinkPersistInfo[] barButtonItemsEquipment = new LinkPersistInfo[dataTableEquipment != null ? dataTableEquipment.Rows.Count : 0];
                DevExpress.XtraBars.BarItem[] barItems = new BarItem[
                    (dataTable != null ? dataTable.Rows.Count : 0)
                    + (dataTableEquipment != null ? dataTableEquipment.Rows.Count : 0)];
                int indexButton = 0;
                int linkButton = 0;
                if (dataTable != null)
                {
                    foreach (DataRow item in dataTable.Rows)
                    {
                        DevExpress.XtraBars.BarButtonItem barButtonItem = new DevExpress.XtraBars.BarButtonItem();
                        barButtonItem.Caption = item["projectName"].ToString();
                        barButtonItem.Name = "barButtonItemProject" + item["id"].ToString();
                        barButtonItem.Tag = item["id"];
                        barButtonItem.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.barButtonItemPopuMenu_ItemClick);

                        barButtonItem.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
                        barButtonItem.GroupIndex = 1;
                        barButtonItemsProject[linkButton++] = new LinkPersistInfo(barButtonItem);
                        barItems[indexButton++] = barButtonItem;
                    }
                }
                if (dataTableEquipment != null)
                {
                    this.equipmentAddress = int.Parse(dataTableEquipment.Rows[0]["id"].ToString());
                    linkButton = 0;
                    foreach (DataRow item in dataTableEquipment.Rows)
                    {
                        DevExpress.XtraBars.BarButtonItem barButtonItem = new DevExpress.XtraBars.BarButtonItem();
                        barButtonItem.Caption = item["equipmentName"].ToString();
                        barButtonItem.Name = "barButtonItemEquip" + item["id"].ToString();
                        barButtonItem.Tag = item["id"];
                        barButtonItem.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.barButtonItemEquipment_ItemClick);

                        barButtonItem.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
                        barButtonItem.GroupIndex = 1;
                        barButtonItemsEquipment[linkButton++] = new LinkPersistInfo(barButtonItem);
                        barItems[indexButton++] = barButtonItem;
                    }
                }

                ((System.ComponentModel.ISupportInitialize)(this.popupMenu1)).BeginInit();
                ((System.ComponentModel.ISupportInitialize)(this.popupMenu2)).BeginInit();
                ((System.ComponentModel.ISupportInitialize)(this.barManager1)).BeginInit();
                this.popupMenu1.ClearLinks();
                this.popupMenu2.ClearLinks();
                this.barManager1.Items.Clear();
                this.popupMenu1.LinksPersistInfo.AddRange(barButtonItemsProject);
                this.popupMenu2.LinksPersistInfo.AddRange(barButtonItemsEquipment);
                this.barManager1.Items.AddRange(barItems);
                ((System.ComponentModel.ISupportInitialize)(this.barManager1)).EndInit();
                ((System.ComponentModel.ISupportInitialize)(this.popupMenu2)).EndInit();
                ((System.ComponentModel.ISupportInitialize)(this.popupMenu1)).EndInit();
                SetPopupMenu(dataTable.Rows[0]["id"].ToString());
            }
            dataTable.Dispose();
            dataTableEquipment.Dispose();
        }

        private void barButtonItemEquipment_ItemClick(object sender, ItemClickEventArgs e)
        {
            string id = (e.Item as BarButtonItem).Tag.ToString();
            if (id != null && id.Length > 0)
                equipmentAddress = int.Parse(id.ToString());
        }

        private void SetPopupMenu(string id)
        {
            string Sql = string.Format(@"Select
fileStream
From vou_project_picture
Where mainId = '{0}'
Order by sortNo", id);

            DataTable dataTablePic = class_MySqlDataBase.GetDataTable(Sql);
            if (dataTablePic != null && dataTablePic.Rows.Count > 0)
            {
                this.imageSlider1.Images.Clear();
                foreach (DataRow item in dataTablePic.Rows)
                {
                    byte[] vs = item["fileStream"] as byte[];
                    this.imageSlider1.Images.Add(ReturnPhoto(vs));
                }
            }
            dataTablePic.Dispose();
        }
        private void barButtonItemPopuMenu_ItemClick(object sender, ItemClickEventArgs e)
        {
            string id = (e.Item as BarButtonItem).Tag.ToString();
            if (id != null && id.Length > 0)
                SetPopupMenu(id);
        }

        private void SetChartControl(ChartControl chartControl, string Title, int Count, string SeriesText, int XWidth)
        {
            chartControl.Width = XWidth;
            chartControl.BorderOptions.Thickness = 10;
            chartControl.CrosshairEnabled = DevExpress.Utils.DefaultBoolean.True;
            chartControl.DataBindings = null;
            chartControl.Legend.AlignmentHorizontal = DevExpress.XtraCharts.LegendAlignmentHorizontal.Left;
            chartControl.Legend.AlignmentVertical = DevExpress.XtraCharts.LegendAlignmentVertical.TopOutside;
            chartControl.Legend.Direction = DevExpress.XtraCharts.LegendDirection.LeftToRight;
            chartControl.Legend.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            chartControl.Legend.Name = "Default Legend";
            chartControl.Legend.UseCheckBoxes = true;
            chartControl.Series.Clear();
            DevExpress.XtraCharts.Series[] series = new DevExpress.XtraCharts.Series[Count];
            for (int i = 0; i < Count; i++)
            {
                series[i] = SetSerise(i, SeriesText);
            }
            chartControl.SeriesSerializable = series;
            DevExpress.XtraCharts.ChartTitle chartTitle3 = new DevExpress.XtraCharts.ChartTitle();
            chartTitle3.Dock = DevExpress.XtraCharts.ChartTitleDockStyle.Bottom;
            chartTitle3.Text = Title;
            chartControl.Titles.Clear();
            chartControl.Titles.Add(chartTitle3);

            SwiftPlotDiagram diagram = chartControl.Diagram as SwiftPlotDiagram;
            diagram.AxisX.GridLines.Visible = true;
            diagram.AxisX.Label.TextPattern = "{A:hh:mm:ss}";
            diagram.AxisX.Title.Text = "时间";
            diagram.AxisX.VisibleInPanesSerializable = "-1";
            diagram.AxisY.Interlaced = true;
            //diagram.AxisY.Title.Text = "数值";
            //diagram.AxisY.VisibleInPanesSerializable = "-1";
            diagram.AxisY.WholeRange.AlwaysShowZeroLevel = false;
            diagram.Margins.Right = 5;
            diagram.Margins.Left = 5;
            diagram.Margins.Top = 2;
            diagram.Margins.Bottom = 2;
            chartControl.MouseUp += new System.Windows.Forms.MouseEventHandler(this.PopupMenu2Show);
        }
        private DevExpress.XtraCharts.Series SetSerise(int count, string SeriesText)
        {
            DevExpress.XtraCharts.Series series = new DevExpress.XtraCharts.Series();
            DevExpress.XtraCharts.SwiftPlotSeriesView swiftPlotSeriesView1 = new DevExpress.XtraCharts.SwiftPlotSeriesView();
            series.ArgumentScaleType = DevExpress.XtraCharts.ScaleType.DateTime;
            series.Name = SeriesText + (2 - count);
            series.View = swiftPlotSeriesView1;
            series.CheckedInLegend = count > 0 ? false : true;
            return series;
        }

        private void Form_welCome_Load(object sender, EventArgs e)
        {
            this.form_NewMain.SendMsgEvent += this.SocketNewDataReceive;
        }

        private DataTable GetDataTable(string Index)
        {
            DataTable dataTable = new DataTable();
            DataColumn FieldName = new DataColumn("FieldName", typeof(string));
            DataColumn FieldRemark = new DataColumn("FieldRemark", typeof(string));
            dataTable.Columns.Add(FieldName);
            dataTable.Columns.Add(FieldRemark);

            for (int i = 0; i < 150; i++)
            {
                DataRow newRow = dataTable.NewRow();
                newRow[0] = string.Format("FieldName", i + 1);
                newRow[1] = string.Format("FieldRemark:{1}", i + 1, Index);
                dataTable.Rows.Add(newRow);
            }
            return dataTable;
        }
        private void function2()
        {
            int i = 0;
            DocReplaceModel[] docReplaceModels = new DocReplaceModel[4];

            try
            {
                docReplaceModels[i++] = new DocReplaceModel("Name", "梁昊");
                docReplaceModels[i++] = new DocReplaceModel("YEAR", "2020");
                docReplaceModels[i++] = new DocReplaceModel("MONTH", "07");
                docReplaceModels[i++] = new DocReplaceModel("DAY", "05");

                Class_WordOut class_WordOut = new Class_WordOut();
                string fileName = class_WordOut.OutWord("D01", docReplaceModels);
                if (File.Exists(fileName))
                    System.Diagnostics.Process.Start(@fileName);
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
            }
        }


        private void Form_welCome_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.form_NewMain.SendMsgEvent -= this.SocketNewDataReceive;
        }

        private System.Drawing.Image ReturnPhoto(byte[] streamByte)
        {
            MemoryStream ms = new MemoryStream(streamByte);
            return System.Drawing.Image.FromStream(ms);
        }

        private void Form_welCome_Shown(object sender, EventArgs e)
        {
            SetCompoment();
        }

        private void imageSlider1_MouseUp(object sender, MouseEventArgs e)
        {
            //点左键无效, 必须是点右键弹出菜单
            if (e.Button == MouseButtons.Right)
            {
                this.popupMenu1.ShowPopup(Control.MousePosition);
            }
        }

        private void PopupMenu2Show(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                this.popupMenu2.ShowPopup(Control.MousePosition);
            }
        }
    }
}
